package cn.edu.hyit.zhao.action;

import java.sql.Timestamp;
import java.util.Date;
import java.util.List;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.opensymphony.xwork2.ActionSupport;

import cn.edu.hyit.zhao.entity.Log;
import cn.edu.hyit.zhao.entity.Record;
import cn.edu.hyit.zhao.entity.Shop;
import cn.edu.hyit.zhao.service.ILogService;
import cn.edu.hyit.zhao.service.IRecordService;
import cn.edu.hyit.zhao.service.IShopService;
import cn.edu.hyit.zhao.utils.Md5Utils;

@ParentPackage(value = "intercept-default") // extend this package include
					    // the‘json-default’
@Scope(value = "prototype") // for evey request to new instance
@Namespace("/user") // this is resource space address
@Results({ @Result(name = ActionSupport.SUCCESS, type = "json"), @Result(name = ActionSupport.ERROR, type = "json") })
// define the response forward resource
@SuppressWarnings("serial")
public class UserAction extends ActionSupport {
    // log instance
    private Logger logger = Logger.getLogger(this.getClass());

    // service
    @Autowired
    private IShopService shopService;
    @Autowired
    private IRecordService recordService;
    @Autowired
    private ILogService logService;

    // return data object
    private JSONObject json;

    // requsets params
    private String username;
    private String password;

    private String newPassword;
    private String confrimPassword;

    private String shopName;
    private Integer controlId;
    private Date limitTime;
    private String status;

    private Integer shopId;

    private Timestamp start;
    private Timestamp end;

    public Timestamp getStart() {
	return start;
    }

    public void setStart(Timestamp start) {
	this.start = start;
    }

    public Timestamp getEnd() {
	return end;
    }

    public void setEnd(Timestamp end) {
	this.end = end;
    }

    public Integer getShopId() {
	return shopId;
    }

    public void setShopId(Integer shopId) {
	this.shopId = shopId;
    }

    public String getShopName() {
	return shopName;
    }

    public void setShopName(String shopName) {
	this.shopName = shopName;
    }

    public Integer getControlId() {
	return controlId;
    }

    public void setControlId(Integer controlId) {
	this.controlId = controlId;
    }

    public Date getLimitTime() {
	return limitTime;
    }

    public void setLimitTime(Date limitTime) {
	this.limitTime = limitTime;
    }

    public String getStatus() {
	return status;
    }

    public void setStatus(String status) {
	this.status = status;
    }

    public String getNewPassword() {
	return newPassword;
    }

    public void setNewPassword(String newPassword) {
	this.newPassword = newPassword;
    }

    public String getConfrimPassword() {
	return confrimPassword;
    }

    public void setConfrimPassword(String confrimPassword) {
	this.confrimPassword = confrimPassword;
    }

    public String getUsername() {
	return username;
    }

    public void setUsername(String username) {
	this.username = username;
    }

    public String getPassword() {
	return password;
    }

    public void setPassword(String password) {
	this.password = password;
    }

    public JSONObject getJson() {
	return json;
    }

    public void setJson(JSONObject json) {
	this.json = json;
    }

    /**
     * define the router in the namespace to handle request，the @result is
     * return data type and this params is a KEY-VALUE type. the json data
     * should follow the convention
     * References:http://tutuge.me/2016/05/02/design-json-api-respoense/
     * 
     * @return
     */
    @Action(value = "login", results = { @Result(type = "json", params = { "includeProperties", "json.*" }) })
    public String login() {
	json = new JSONObject();
	JSONObject data = new JSONObject();
	Shop shop = shopService.getShop(username);
	if (null != shop) {
	    if ("1".equals(shop.getStatus())) {
		if (shop.getPassword().toLowerCase().equals(Md5Utils.parseStrToMd5L32(password))) {
		    // login success,put user info to session
		    ServletActionContext.getRequest().getSession().setAttribute("user", shop);
		    // put user info to json data
		    data = (JSONObject) JSONObject.toJSON(shop);
		    data.remove("password"); // remove password form return data
		    json.put("msg", "登陆成功");
		    json.put("code", 200);
		} else {
		    json.put("msg", "密码错误");
		    json.put("code", 201);
		}
	    } else {
		json.put("msg", "用户已被冻结");
		json.put("code", 203);
	    }
	} else {
	    json.put("msg", "用户不存在");
	    json.put("code", 204);
	}
	json.put("data", data);
	return SUCCESS;
    }

    @Action(value = "password", results = { @Result(type = "json", params = { "includeProperties", "json.*" }) })
    public String changePassword() {
	json = new JSONObject();
	JSONObject data = new JSONObject();
	Shop shop = (Shop) ServletActionContext.getRequest().getSession().getAttribute("user");
	if (null != shop) {
	    if (shop.getPassword().toLowerCase().equals(Md5Utils.parseStrToMd5L32(password))) {
		shop.setPassword(Md5Utils.parseStrToMd5L32(newPassword));
		// update user info
		if (shopService.updateShop(shop) > 0) {
		    json.put("msg", "密码修改成功");
		    json.put("code", 200);
		} else {
		    json.put("msg", "密码修改失败");
		    json.put("code", 205);
		}
	    } else {
		logger.error("用户密码修改错误,用户信息:" + shop + ",参数信息:" + password + "," + newPassword + "," + confrimPassword);
		json.put("msg", "原始密码错误");
		json.put("code", 206);
	    }
	} else {
	    json.put("msg", "会话已经失效，请重新登陆");
	    json.put("code", 400);
	}
	json.put("data", data);
	return SUCCESS;
    }

    @Action(value = "queryRecordRecent10", results = {
	    @Result(type = "json", params = { "includeProperties", "json.*" }) })
    public String queryRecordRecent10() {
	json = new JSONObject();
	JSONArray data = new JSONArray();
	Shop shop = (Shop) ServletActionContext.getRequest().getSession().getAttribute("user");
	if (null != shop) {
	    List<Record> records = recordService.queryRecordListByShopId(shop.getShopId());
	    data = (JSONArray) JSONArray.toJSON(records);
	    json.put("msg", "查询成功");
	    json.put("code", 200);
	} else {
	    json.put("msg", "会话已经失效，请重新登陆");
	    json.put("code", 400);
	}
	json.put("data", data);
	return SUCCESS;
    }

    @Action(value = "addNewShop", results = { @Result(type = "json", params = { "includeProperties", "json.*" }) })
    public String addNewShop() {
	json = new JSONObject();
	JSONArray data = new JSONArray();
	Shop shop = (Shop) ServletActionContext.getRequest().getSession().getAttribute("user");
	if (null != shop) {
	    Shop newShop = new Shop();
	    newShop.setShopName(shopName);
	    newShop.setUsername(username);
	    newShop.setPassword(Md5Utils.parseStrToMd5L32(password));
	    newShop.setControlId(controlId);
	    newShop.setLimitTime(limitTime);
	    newShop.setStatus(status);
	    newShop.setCreateTime(new Date());
	    newShop.setParentId(shop.getShopId());
	    // to save the new shop
	    int res = shopService.saveShop(newShop);
	    if (res > 0) {
		data = (JSONArray) JSONObject.toJSON(newShop);
		json.put("msg", "新建用户成功");
		json.put("code", 200);
	    } else if (res == -1) {
		json.put("msg", "该用户名已经存在");
		json.put("msg", 207);
	    } else {
		logger.error("新建用户失败，当前登录用户:" + shop + ",新建目标用户：" + newShop);
		json.put("msg", "新建用户失败");
		json.put("code", 208);
	    }
	} else {
	    json.put("msg", "会话已经失效，请重新登陆");
	    json.put("code", 400);
	}
	json.put("data", data);
	return SUCCESS;
    }

    @Action(value = "queryBranchShop", results = { @Result(type = "json", params = { "includeProperties", "json.*" }) })
    public String queryBranchShop() {
	json = new JSONObject();
	JSONArray data = new JSONArray();
	Shop shop = (Shop) ServletActionContext.getRequest().getSession().getAttribute("user");
	if (null != shop) {
	    List<Shop> branchShops = shopService.getBranchShops(shop);
	    data = (JSONArray) JSONArray.toJSON(branchShops);
	    json.put("msg", "查询成功");
	    json.put("code", 200);
	} else {
	    json.put("msg", "会话已经失效，请重新登陆");
	    json.put("code", 400);
	}
	json.put("data", data);
	return SUCCESS;
    }

    @Action(value = "stopShop", results = { @Result(type = "json", params = { "includeProperties", "json.*" }) })
    public String stopShop() {
	json = new JSONObject();
	JSONObject data = new JSONObject();
	Shop shop = (Shop) ServletActionContext.getRequest().getSession().getAttribute("user");
	if (null != shop) {
	    Shop branchShop = shopService.getShop(shopId);
	    if (null != branchShop) {
		branchShop.setStatus("0");
		if (shopService.updateShop(branchShop) > 0) {
		    json.put("msg", "冻结成功");
		    json.put("code", 200);
		} else {
		    logger.error("冻结用户失败，当前登录用户:" + shop + ",操作用户:" + branchShop);
		    json.put("msg", "冻结失败");
		    json.put("code", 209);
		}
	    } else {
		json.put("msg", "不存在的用户");
		json.put("code", 210);
	    }
	} else {
	    json.put("msg", "会话已经失效，请重新登陆");
	    json.put("code", 400);
	}
	json.put("data", data);
	return SUCCESS;
    }

    @Action(value = "startShop", results = { @Result(type = "json", params = { "includeProperties", "json.*" }) })
    public String startShop() {
	json = new JSONObject();
	JSONObject data = new JSONObject();
	Shop shop = (Shop) ServletActionContext.getRequest().getSession().getAttribute("user");
	if (null != shop) {
	    Shop branchShop = shopService.getShop(shopId);
	    if (null != branchShop) {
		branchShop.setStatus("1");
		if (shopService.updateShop(branchShop) > 0) {
		    json.put("msg", "解冻成功");
		    json.put("code", 200);
		} else {
		    logger.error("解冻用户失败，当前登录用户:" + shop + ",操作用户:" + branchShop);
		    json.put("msg", "解冻失败");
		    json.put("code", 209);
		}
	    } else {
		json.put("msg", "不存在的用户");
		json.put("code", 210);
	    }
	} else {
	    json.put("msg", "会话已经失效，请重新登陆");
	    json.put("code", 400);
	}
	json.put("data", data);
	return SUCCESS;
    }

    @Action(value = "queryLoginLog", results = { @Result(type = "json", params = { "includeProperties", "json.*" }) })
    public String queryLoginLog() {
	json = new JSONObject();
	JSONArray data = new JSONArray();
	Shop shop = (Shop) ServletActionContext.getRequest().getSession().getAttribute("user");
	if (null != shop) {
	    // default uri is query login
	    List<Log> logs = logService.getLast10LoginLog(null, shop.getUsername());
	    data = (JSONArray) JSONArray.toJSON(logs);
	    json.put("msg", "查询成功");
	    json.put("code", 200);
	} else {
	    json.put("msg", "会话已经失效，请重新登陆");
	    json.put("code", 400);
	}
	json.put("data", data);
	return SUCCESS;
    }

    @Action(value = "queryRecordByStartEndTime", results = {
	    @Result(type = "json", params = { "includeProperties", "json.*" }) })
    public String queryRecordByStartEndTime() {
	json = new JSONObject();
	JSONArray data = new JSONArray();
	Shop shop = (Shop) ServletActionContext.getRequest().getSession().getAttribute("user");
	if (null != shop) {
	    // default uri is query login
	    List<Record> records = recordService.queryRecordListByStartEndTime(start, end);
	    data = (JSONArray) JSONArray.toJSON(records);
	    json.put("msg", "查询成功");
	    json.put("code", 200);
	} else {
	    json.put("msg", "会话已经失效，请重新登陆");
	    json.put("code", 400);
	}
	json.put("data", data);
	return SUCCESS;
    }
}
